<template lang="pug">
.form.video(v-loading="loading")
  .form-header
    .form-header-logo
      img(src="../../static/images/logo_black.png")
    .form-header-title 有料系统管理平台
  .form-content
    .form-body
      el-popover(
        ref="quillImageHandle"
        popper-class="image-popover"
        width="120"
        trigger="click"
      )
        .image-item(@click="selectUpload") 本地上传
        .image-item(@click="selectVideo") 视频库视频
      .form-title
        el-input.form-el-input(placeholder='请在这里输入标题' v-model="form.title" maxlength='64' show-word-limit)
      .form-section-author
        el-input.form-el-input(placeholder='请输入作者' v-model="form.author" maxlength='8' show-word-limit)
      .form-textarea
        el-input(
          placeholder='请在这里输入内容'
          type="textarea"
          rows="30"
          resize="none"
          v-model="form.content"
          maxlength='300'
          show-word-limit
        )
      .form-video-bd
        .styles-item-btn#video-handle(@click="addVideo" v-if="!form.fileUrl")
          .el-icon-plus
          span 添加视频
        .video-content
          .video-item
            video(:src="form.fileUrl" controls)
            .video-item-handle#video-item-handle(@click="changeVideo")
              .iconfont.icon-switch
      .form-section
        .form-section-header
          .form-section-title 相关材料
          .form-section-info 为文章添加相关的材料（最多可添加10款材料）
        .form-section-body.flex
          .styles-item-btn(@click="selectMaterial")
              .el-icon-plus
              span 从材料库中选择
          .material-item(
            v-for="item in form.materialList"
            :style="`background-image: url(${item.picImg})`"
          )
            .material-item-name {{ item.materialName }}
            .iconfont.el-icon-circle-close(@click="delMaterial(item, index)")
      .form-section
        .form-section-header
          .form-section-title 封面
          .form-section-info 为文章设置封面
        .form-section-body.flex
          .styles-item-btn(@click="selectImage('cover')")
            .el-icon-plus
            span 从图片库中选择
          .form-cover(v-if="form.coverImageUrl" :style="`background-image: url(${form.coverImageUrl})`")
            .iconfont.el-icon-circle-close(@click="delCover")
      .form-section.form-section-cate
        .form-section-header
          .form-section-title 分类
          .form-section-info 填写准确的文章分类，可以让文章有更多被发现的机会。
        .form-section-body
          el-select(v-model="form.categoryId")
            el-option(v-for="item in cateList" :label="item.categoryName" :value="item.articleCategoryId" :key="item.articleCategoryId")
  .form-footer
    el-button(size="small" @click="save('draft')") 保存为草稿
    el-button(size="small" name="warning" @click="save('preview')") 预览
    el-button(size="small" type="primary" @click="save('publish')") 发布
  .edit-hidden-upload(v-show="false")
    el-upload(
      action="#"
      class="upload-demo"
      :multiple="true"
      accept="video/*"
      ref="hiddenUpload"
      :show-file-list="false"
      :auto-upload="false"
      :on-change="handleQuillChange"
    )
      el-button(size="small" name="primary" slot="trigger") 上传图片
  select-cover-modal(:show="showCoverModal" @close="closeCoverModal" @change="changeCover")
  select-material-modal(:show="showMaterialModal" :materialList="form.materialList" @close="closeMaterialModal" @confirm="changeSourceList")
  select-video-modal(:show="showVideoModal" @close="closeVideoModal" @change="changeVideoItem")
</template>

<script>
import selectCoverModal from './components/selectCoverModal'
import selectMaterialModal from './components/selectMaterialModal'
import selectVideoModal from './components/selectVideoModal'
import { FileUpload, getArticleCategoryList, saveOrPublishArticle, getArticleDetail, getVideoSourceMaterialDetail } from 'api'
import { mapActions } from 'vuex'
export default {
  name: 'editVideo',
  data () {
    return {
      form: {
        title: '',
        author: '',
        content: '',
        coverImageUrl: '',
        coverImage: '',
        fileUrl: '',
        materialList: [],
        sourceMaterialList: [],
        categoryId: ''
      },
      loading: false,
      cateList: [],
      showCoverModal: false,
      showMaterialModal: false,
      showVideoModal: false,
      sourceId: ''
    }
  },
  components: {
    selectCoverModal,
    selectMaterialModal,
    selectVideoModal
  },
  methods: {
    ...mapActions([
      'changePreviewParams'
    ]),
    delMaterial (item, index) {
      this.form.materialList.splice(index, 1)
    },
    delCover () {
      this.form.coverImageUrl = ''
      this.form.coverImage = ''
    },
    selectVideo () {
      this.$refs.quillImageHandle.doClose()
      this.showVideoModal = true
    },
    closeVideoModal () {
      this.showVideoModal = false
    },
    changeVideoItem (item) {
      if (item.type === 'custom') {
        this.form.sourceMaterialList = [item]
      }
      this.form.fileId = item.fileId
      this.form.fileUrl = item.fileUrl
      this.showVideoModal = false
    },
    selectMaterial () {
      this.showMaterialModal = true
    },
    closeMaterialModal () {
      this.showMaterialModal = false
    },
    changeSourceList (list) {
      this.form.materialList.push(...list)
      this.showMaterialModal = false
    },
    changeVideo () {
      if(this.$refs && this.$refs.quillImageHandle) {
        this.$refs.quillImageHandle.referenceElm = document.getElementById("video-item-handle")
        this.$refs.quillImageHandle.doToggle()
      }
    },
    selectUpload (state) {
      this.$refs.quillImageHandle.doClose()
      if (state) {
        this.$refs.hiddenUpload.$children[0].$refs.input.click()
      }
    },
    selectImage () {
      this.showCoverModal = true
    },
    closeCoverModal () {
      this.showCoverModal = false
    },
    changeCover (item) {
      this.form.coverImage = item.fileId
      this.form.coverImageUrl = item.fileUrl
      this.showCoverModal = false
    },
    // 富文本图片上传
    async handleQuillChange (file, fileList) {
      try {
        let fileObj = await this.fileUpload(file.raw)
        let host = window.location.hostname === '123.58.39.242' || window.location.hostname === '192.168.2.71' ? 'https://ja-material-formal.oss-cn-shenzhen.aliyuncs.com' : 'https://ja-material-test.oss-cn-shenzhen.aliyuncs.com'
        this.form.fileUrl = `${host}${fileObj.fileUrl}`
        this.form.fileId = fileObj.fileId
        this.form.sourceMaterialList = [{ fileId: fileObj.fileId, title: fileObj.fileName, fileUrl: `${host}${fileObj.fileUrl}`, type: 'custom' }]
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async fileUpload (raw) {
      return new Promise(async (resolve, reject) => {
        try {
          let formData = new FormData()
          formData.append('Filedata', raw)
          formData.append("applicationId", 4)
          const { ResultSet } = await this.$axios.post(FileUpload, { formData: formData, isUpload: true }, { headers:{ "Content-Type": "multipart/form-data" } })
          resolve({ ...ResultSet.Result[0] })
        } catch (err) {
          console.log(err)
          reject(err)
        }
      })
    },
    addVideo () {
      if(this.$refs && this.$refs.quillImageHandle) {
        this.$refs.quillImageHandle.referenceElm = document.getElementById("video-handle")
        this.$refs.quillImageHandle.doToggle()
      }
    },
    async getCateList () {
      try {
        const { ResultSet } = await this.$axios.post(getArticleCategoryList)
        this.cateList = ResultSet.userData.data
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getDetail () {
      try {
        const { ResultSet } = await this.$axios.post(getArticleDetail, { articleId: this.form.articleId })
        this.form = { ...this.form, ...ResultSet.userData.detail }
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getSourceMaterialList () {
      try {
        const { ResultSet } = await this.$axios.post(getVideoSourceMaterialDetail, { sourceMaterialId: this.sourceId })
        this.form = { ...this.form, ...ResultSet.userData.detail, content: ResultSet.userData.detail.videoDetail }
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async save (isPublish) {
      try {
        if (!this.form.title) {
          this.$message.error('请输入文章标题！')
          return
        }
        if (isPublish === 'preview') {
          localStorage.setItem('previewParams', JSON.stringify({...this.form}))
          let routeUrl = this.$router.resolve({
            name: 'previewVideo'
          })
          window.open(routeUrl.href, '_blank')
        } else {
          let query = { ...this.form }
          if (isPublish === 'draft') {
            query.isPublish = false
          } else {
            if (!this.form.author) {
              this.$message.error('请输入文章作者！')
              return
            }
            if (!this.form.content) {
              this.$message.error('请编辑文章正文！')
              return
            }
            if (!this.form.materialList.length) {
              this.$message.error('请选择相关材料！')
              return
            }
            if (!this.form.coverImageUrl) {
              this.$message.error('请选择文章封面！')
              return
            }
            if (!this.form.categoryId) {
              this.$message.error('请选择文章分类！')
              return
            }
            query.isPublish = true
          }
          this.loading = true
          query.materialIds = query.materialList.map(item => item.materialId || item.id)
          if (query.sourceMaterialList.length) {
            query.sourceMaterialList.forEach(item => {
              if (item.type === 'custom') {
                item.name = '未命名视频'
                item.title = query.title
                item.videoDetail = query.content
                item.coverImage = query.coverImage
              }
            })
          }
          query.type = 2
          await this.$axios.post(saveOrPublishArticle, { ...query })
          this.loading = false
          if (isPublish === 'publish') {
            this.$router.replace({ name: 'articleManage' })
          } else {
            this.$message.success('保存成功！')
          }
        }
      } catch (err) {
        this.loading = false
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getCateList()
      if (to.params.id) {
        vm.form.articleId = to.params.id
        vm.getDetail()
      }
      if (to.query.sourceId) {
        vm.sourceId = to.query.sourceId
        vm.getSourceMaterialList()
      }
    })
  }
}
</script>

<style lang="scss">
.form-el-input {
  .el-input__inner {
    height: 100%;
    width: 100%;
    padding: 0;
    border: none !important;
    &::placeholder {
      color: rgb(117, 117, 117);
    }
  }
}
.form-textarea {
  .el-textarea {
    width: 100%;
    height: 100%;
  }
  .el-textarea__inner {
    height: 100%;
    width: 100%;
    padding: 0;
    border: none !important;
    font-size: 14px;
    color: #353535;
    &::placeholder {
      font-size: 14px;
      color: rgb(117, 117, 117);
    }
  }
}
</style>

<style lang="scss" scoped>
.video {
  min-width: 1260px;
}
.form-header {
  height: 54px;
  width: 100%;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 10px;
}
.form-header-logo {
  height: 100%;
  img {
    max-height: 100%;
  }
}
.form-header-title {
  margin-left: 25px;
  font-size: 24px;
  color: #363636;
}
.form-content {
  padding: 30px 0 0;
  .form-body {
    width: 770px;
    margin: 0 auto;
    padding: 55px 96px;
    background: #fff;
  }
}
.form-title {
  .el-input {
    width: 100%;
    text-align: left;
    font-size: 25px;
    color: #353535;
  }
}
.form-section-author {
  margin-top: 20px;
  .el-input {
    width: 100%;
    text-align: left;
    font-size: 14px;
    color: #353535;
  }
}
.form-textarea {
  margin-top: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #DCDFE6;
  min-height: 600px;
  .el-textarea__inner {
    width: 100%;
    height: 100%;
    font-size: 14px;
    border: none !important;
  }
}
.styles-item-btn {
  width: 150px;
  height: 150px;
  border: 1px dashed #DCDFE6;
  border-radius: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 25px;
  margin-bottom: 30px;
  color: #B2B4C7;
  cursor: pointer;
  &.margin-none {
    margin-bottom: 0;
  }
  span {
    display: inline-block;
    margin-left: 5px;
  }
}
.form-video-bd {
  margin-top: 30px;
}
.form-section-header {
  display: flex;
  align-items: center;
}
.form-section-title {
  font-size: 14px;
  color: #363636;
}
.form-section-info {
  margin-left: 8px;
  font-size: 12px;
  color: #999;
}
.form-section-body {
  margin-top: 15px;
  &.file-cover {
    .styles-item-btn {
      margin-bottom: 0;
    }
  }
  &.flex {
    display: flex;
    flex-wrap: wrap;
  }
}
.form-cover {
  position: relative;
  width: 150px;
  height: 150px;
  border-radius: 4px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  .iconfont {
    font-size: 24px;
    position: absolute;
    top: 0;
    right: 0;
    transform: translate(50%, -50%);
    color: #FF2E42;
  }
}
.material-item {
  position: relative;
  width: 150px;
  height: 150px;
  border-radius: 4px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  margin-bottom: 25px;
  margin-right: 30px;
  .iconfont {
    font-size: 24px;
    position: absolute;
    top: 0;
    right: 0;
    transform: translate(50%, -50%);
    color: #FF2E42;
  }
}
.material-item-name {
  position: absolute;
  left: 0;
  bottom: 0;
  height: 32px;
  line-height: 32px;
  width: 100%;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 0px 0px 4px 4px;
  padding: 0 10px;
  font-size: 14px;
  color: #fff;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
}
.image-item {
  padding: 10px 20px;
  cursor: pointer;
}
.video-item {
  width: 100%;
  position: relative;
  video {
    width: 100%;
  }
  .video-item-handle {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 26px;
    height: 26px;
    border: 1px solid #DCDFE6;
    background: #FFFFFF;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    .iconfont {
      font-size: 16px;
      color: #999999;
    }
  }
}
.video-content {
  margin-bottom: 30px;
}
.form-footer {
  width: 770px;
  margin: 0 auto;
  padding: 25px 60px;
  border-top: 1px solid #DCDFE6;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>